package com.bitin.adorn.config.captcha;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.awt.*;

/**
 * 验证码自动装配配置
 *
 * @author Mr.Lu
 * @since 2024/12/26 14:59
 */
@Configuration
public class CaptchaConfig {

    private final CaptchaProperties captchaProperties;

    @Autowired
    public CaptchaConfig(CaptchaProperties captchaProperties) {
        this.captchaProperties = captchaProperties;
    }

    /**
     * 验证码文字生成器
     *
     * @return CodeGenerator
     */
    @Bean
    public CodeGenerator codeGenerator() {
        String type = captchaProperties.getCode().getType().toLowerCase();
        int length = captchaProperties.getCode().getLength();
        return switch (type) {
            case "math" -> new MathGenerator(length);
            case "random" -> new RandomGenerator(length);
            default -> throw new IllegalArgumentException("Invalid captcha codegen type: " + type);
        };
    }

    /**
     * 验证码字体
     */
    @Bean
    public Font captchaFont() {
        String name = captchaProperties.getFont().getName();
        int size = captchaProperties.getFont().getSize();
        int wight = captchaProperties.getFont().getWeight();
        return new Font(name, wight, size);
    }
}
